<template>
    <view>
        <view class="form-container">
            <!-- USB设备选择 -->
            <view class="form-item">
                <text class="label">USB设备：</text>
                <picker :range="usbDevices" :value="usbDeviceIdIndex" @change="onPaperUSBDevice">
                    <view class="picker">{{ form.usbDeviceName || '请选择USB设备' }}</view>
                </picker>
            </view>

            <!-- 打印数量 -->
            <view class="form-item">
                <text class="label">打印数量：</text>
                <input class="input" type="number"
                       v-model="form.numofcopies"
                       placeholder="请输入打印数量"
                       :disabled="isUsbDeviceDisabled"
                       :class="{ 'disabled-picker': isUsbDeviceDisabled }">
            </view>

            <!-- 打印色彩 -->
            <view class="form-item">
                <text class="label">打印色彩：</text>
                <picker :disabled="isUsbDeviceDisabled"
                        :class="{ 'disabled-picker': isUsbDeviceDisabled }"
                        :range="printModes" :value="selectedPrintModeIndex" @change="onPrintModeChange">
                    <view class="picker">{{ form.mode || '请选择打印色彩' }}</view>
                </picker>
            </view>

            <!-- 单双面打印 -->
            <view class="form-item">
                <text class="label">单双面打印：</text>
                <picker :disabled="isUsbDeviceDisabled"
                        :class="{ 'disabled-picker': isUsbDeviceDisabled }"
                        :range="duplexOptions" :value="selectedDuplexIndex" @change="onDuplexChange">
                    <view class="picker">{{ form.duplex || '请选择单双面打印' }}</view>
                </picker>
            </view>

            <!-- 逐份打印 -->
            <view class="form-item">
                <text class="label">逐份打印：</text>
                <picker :disabled="isUsbDeviceDisabled"
                        :class="{ 'disabled-picker': isUsbDeviceDisabled }"
                        :range="collateOptions" :value="selectedCollateIndex" @change="onCollateChange">
                    <view class="picker">{{ form.collate || '请选择是否逐份打印' }}</view>
                </picker>
            </view>

            <!-- 纸张尺寸 -->
            <view class="form-item">
                <text class="label">纸张尺寸：</text>
                <picker :disabled="isUsbDeviceDisabled"
                        :class="{ 'disabled-picker': isUsbDeviceDisabled }"
                        :range="paperSizes" :value="selectedPaperSizeIndex" @change="onPaperSizeChange">
                    <view class="picker">{{ form.paper || '请选择纸张尺寸' }}</view>
                </picker>
            </view>

            <!-- 纸张来源 -->
            <view class="form-item">
                <text class="label">纸张来源：</text>
                <picker :disabled="isUsbDeviceDisabled"
                        :class="{ 'disabled-picker': isUsbDeviceDisabled }"
                        :range="feeders" :value="selectedFeederIndex" @change="onFeederChange">
                    <view class="picker">{{ form.feeder || '请选择纸张来源' }}</view>
                </picker>
            </view>

            <!-- 提交按钮 -->
            <view class="form-item">
                <button type="primary" @click="configPrinter" :disabled="isUsbDeviceDisabled">提交</button>
            </view>
            <view style="text-align: center" @click="navigateToPrint">打印测试</view>
        </view>
    </view>
</template>

<script>
const printerModule = uni.requireNativePlugin("PrinterModule")

export default {
    data() {
        return {
            form: {
                usbDeviceId: '',
                usbDeviceName: '',
                numofcopies: '',
                mode: '',
                duplex: '',
                collate: '',
                paper: '',
                feeder: ''
            },
            printModes: [],
            duplexOptions: [],
            collateOptions: [],
            paperSizes: [],
            feeders: [],
            usbDevices: [],
            usbDeviceArr: [],
            usbDeviceIdIndex: '',
            selectedPrintModeIndex: '',
            selectedDuplexIndex: '',
            selectedCollateIndex: '',
            selectedPaperSizeIndex: '',
            selectedFeederIndex: '',
        }
    },
    computed: {
        // 计算属性来判断USB设备是否被选择，用于禁用其他选项
        isUsbDeviceDisabled() {
            return !this.form.usbDeviceId;
        }
    },
    mounted() {
        this.getAllUsbDevices();
    },
    methods: {
        /**测试打印界面*/
        navigateToPrint() {
            uni.navigateTo({
                url: '/pages/printText/printText'
            });
        },
        onPaperUSBDevice(event) {
            const selectedDevice = this.usbDeviceArr[event.detail.value];

            if (!selectedDevice) {
                uni.showToast({
                    title: '请选择USB设备',
                    icon: 'error',
                    duration: 2000
                });

                return;
            }

            const result = printerModule.handleSetPrinter({
                usbDeviceId: selectedDevice.deviceId
            })

            if (result && result.success) {
                this.form.usbDeviceId = selectedDevice.deviceId;
                this.form.usbDeviceName = selectedDevice.deviceName;

                setTimeout(() => {
                    this.getPrinterAbility();
                })
            }
        },

        onPrintModeChange(event) {
            this.selectedPrintModeIndex = event.detail.value;
            this.form.mode = this.printModes[this.selectedPrintModeIndex];
        },

        onDuplexChange(event) {
            this.selectedDuplexIndex = event.detail.value;
            this.form.duplex = this.duplexOptions[this.selectedDuplexIndex];
        },

        onCollateChange(event) {
            this.selectedCollateIndex = event.detail.value;
            this.form.collate = this.collateOptions[this.selectedCollateIndex];
        },

        onPaperSizeChange(event) {
            this.selectedPaperSizeIndex = event.detail.value;
            this.form.paper = this.paperSizes[this.selectedPaperSizeIndex];
        },

        onFeederChange(event) {
            this.selectedFeederIndex = event.detail.value;
            this.form.feeder = this.feeders[this.selectedFeederIndex];
        },

        getAllUsbDevices() {
            const result = printerModule.getAllUsbDevice();
            // const result = { message: "接口调用成功", success: true, data: [{ deviceName: "P2500-series", deviceId: 1002 }] }
            // 处理数据
            this.usbDeviceArr = result.data;
            this.usbDevices = result.data.map(item => item.deviceName);
        },

        getPrinterAbility() {
            const result = printerModule.getPrinterAbility();
            if (result.success) {
                const printerInfoStr = result.data;
                console.log(printerInfoStr)

                if (!printerInfoStr) {
                    uni.showToast({
                        title: '无法获取到打印机信息',
                        duration: 2000
                    });

                    return;
                }

                const printerInfo = JSON.parse(printerInfoStr);

                this.printModes = printerInfo.printsetting.mode;
                this.duplexOptions = printerInfo.printsetting.duplex;
                this.collateOptions = printerInfo.printsetting.collate;
                this.paperSizes = printerInfo.printsetting.paper;
                this.feeders = printerInfo.printsetting.feeder;
            } else {
                uni.showToast({
                    title: result.message,
                    duration: 2000
                });
            }

            // const result = {
            //     printsetting: {
            //         mode: ["bw"],
            //         duplex: ["simplex", "manual_duplex_short_edge", "manual_duplex_long_edge"],
            //         collate: ["collate", "non-collate"],
            //         paper: ["custom_paper", "A4", "A5", "A5_Hor", "Letter", "JIS_B5"],
            //         feeder: ["auto"],
            //         paper_type: ["plain", "tough"],
            //         density: ["lightest", "lighter", "default", "darker", "darkest"]
            //     }
            // }
        },
        configPrinter() {
            const {numofcopies, mode, duplex, collate, paper, feeder} = this.form;
            const prams = {numofcopies, mode, duplex, collate, paper, feeder};
            const result = printerModule.configPrinter(prams);
            // const result = { message: "打印机设置成功", success: true };
            if (result.success) {
                uni.showToast({
                    title: '打印机配置成功!',
                    icon: 'success',
                    duration: 2000
                });
                setTimeout(() => {
                    uni.hideToast();
                }, 2000);
            }
        },
    }
}
</script>

<style scoped>
.form-container {
    padding: 16rpx;
}

.form-item {
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.disabled-picker {
    color: #ccc;
    background-color: #f1f1f1;
    pointer-events: none;
}

.text {
    flex-shrink: 0;
    width: 200rpx;
}

.label {
    /*width: 210rpx;*/
}

.input {
    width: 400rpx;
    border: 1px solid #ccc;
    padding: 10rpx;
}

.picker {
    flex-grow: 1;
    border: 1px solid #ccc;
    padding: 10rpx;
    border-radius: 4rpx;
    width: 400rpx;
    min-width: 400rpx; /* 设置最小宽度，防止宽度缩短 */
    max-width: 100%; /* 保证不会超出父容器 */
    overflow: hidden; /* 如果内容过长，隐藏溢出 */
    text-overflow: ellipsis; /* 显示省略号 */
    white-space: nowrap; /* 防止换行 */
}
</style>
